/*
 * @(#)AdhocQueryConfigProducer.java
 * Date 2013-08-13
 * Version 1.0
 * Author Jim Horner
 * Copyright (c)2012
 */


package us.hornerscorners.lamppost.registry.inject;

import java.io.InputStream;

import javax.enterprise.inject.Produces;

import javax.enterprise.inject.spi.Annotated;
import javax.enterprise.inject.spi.InjectionPoint;

import org.apache.commons.lang3.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.yaml.snakeyaml.Yaml;

import us.hornerscorners.lamppost.exception.ValidationException;

import us.hornerscorners.lamppost.registry.config.AdhocQueryConfig;


/**
 *
 * @author jim
 */
public class AdhocQueryConfigProducer {

    /** Field description */
    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * Method description
     *
     *
     * @param is
     *
     * @return
     */
    public static AdhocQueryConfig readConfig(InputStream is) throws ValidationException {

        Yaml yaml = new Yaml(new AdhocQueryConfigConstructor());
        AdhocQueryConfig result = yaml.loadAs(is, AdhocQueryConfig.class);

        result.validate();

        return result;
    }

    /**
     * Method description
     *
     *
     *
     * @param injectionPoint
     * @return
     * @throws us.hornerscorners.lamppost.exception.ValidationException
     */
    @XDSTarget
    @Produces
    public AdhocQueryConfig produce(InjectionPoint injectionPoint)
            throws ValidationException {

        Annotated ann = injectionPoint.getAnnotated();
        XDSTarget target = ann.getAnnotation(XDSTarget.class);

        String filename = target.value();

        if (StringUtils.isBlank(filename)) {

            String msg = "XDSTarget filename can not be blank.";

            logger.error(msg);

            throw new IllegalArgumentException(msg);
        }

        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        InputStream is = cl.getResourceAsStream(filename);

        if (is == null) {

            String msg = String.format("XDSTarget filename [%s] can not be found.",
                                       filename);

            logger.error(msg);

            throw new IllegalStateException(msg);
        }
        
        logger.debug("Reading query config [{}].", filename);

        return readConfig(is);
    }
}
